package tr.gen._3bit.java._2k1s.web.converter;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import tr.gen._3bit.java._2k1s.dao.model.Model;
import tr.gen._3bit.java._2k1s.dao.service.Service;
import tr.gen._3bit.java._2k1s.web.util.SpringApplicationContext;

/*
 * Basic type conversion operations for model beans.Integer to Model
 * and Model to Integer conversions. This will be called automatically 
 * when processing form inputs.  
 */
public class GenericModelConverter extends StrutsTypeConverter {
	
	@SuppressWarnings("unchecked")
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		Integer id = Integer.parseInt(values[0]);
		String name = toClass.getSimpleName();
		name = Character.toLowerCase(name.charAt(0)) + name.substring(1) + "Service";
		Service srv = (Service) SpringApplicationContext.getBean(name);
		return srv.find(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public String convertToString(Map context, Object o) {
		return ((Model) o).getId().toString();
	}
	
}
